<template>
  <div>
    <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="form.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="form.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          style="width: 80%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in list"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="form.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getEmployees } from "@/api/employees";
import {
  addDepartments,
  chakDepartments,
  updateDepartments,
} from "@/api/departments";
export default {
  props: {
    id: {
      type: String,
      required: true,
    },
    isEdit: {
      type: Boolean,
      required: true,
    },
    originList: {
      type: Array,
      required: true,
    },
  },
  data() {
    // 校验是否编码相同
    const valiCode = (rule, value, callback) => {
      let exsitCodeList = this.originList.map((item) => item.code);
      console.log("exsitCodeList", exsitCodeList);

      // 如果是编辑状态, 需要把当前的部门的编码从已经存在的数组中移出
      if (this.isEdit) {
        exsitCodeList = this.originList
          .filter((item) => item.id !== this.id)
          .map((item) => item.code);
      }

      if (exsitCodeList.includes(value)) {
        // 存在
        callback(new Error(`该部门编码: ${value}已存在, 请重新输入`));
      } else {
        // 不存在放行
        callback();
      }
    };
    // 校验部门名称在同级部门中不能重复
    const valiName = (rule, value, callback) => {
      // 找得到当前点击部门的子部门
      let exstNameList = this.originList
        .filter((item) => item.pid === this.id)
        .map((item) => item.name);
     // 编辑触发&&
      if (this.isEdit) {
        // 获取当前部门的pid 当前部门兄弟
        // 全部数据 ====> 自己与兄弟依据
        const pid = this.originList.find((item) => item.id === this.id).pid;
        // 获取被占用的名称列表
        // 全部的数据中==(筛选)==>自己与兄弟==(筛选)==>将自己排除==(筛选)==>除自己的兄弟
        exstNameList = this.originList
          .filter((item) => item.pid === pid)
          .filter((item) => item.id !== this.id)
          .map((item) => item.name);
      }

      // 判断当前用户输入的部门名称是否存在已经存在的数据
      if (exstNameList.includes(value)) {
        callback(new Error(`该部门名称: ${value}已存在, 请重新输入`));
      } else {
        callback();
      }
    };

    return {
      form: {
        name: "", // 部门名称
        code: "", // 部门编码
        manager: "", // 部门管理者
        introduce: "", // 部门介绍
      },
      list: [], // 储存加载部门负责人的数据
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: "请输入部门的名称", trigger: "blur" },
          {
            min: 1,
            max: 15,
            message: "请输入长度1~15的部门名称",
            trigger: "brur",
          },
          {
            validator: valiName,
            trigger: "blur",
          },
        ],
        code: [
          { required: true, message: "请输入部门的编码", trigger: "blur" },
          {
            min: 1,
            max: 15,
            message: "请输入长度1~15的部门编码",
            trigger: "brur",
          },
          {
            validator: valiCode,
            trigger: "blur",
          },
        ],
        manager: [
          { required: true, message: "请输入部门的负责人", trigger: "blur" },
        ],
        introduce: [
          { required: true, message: "请输入部门的介绍", trigger: "blur" },
          {
            min: 1,
            max: 300,
            message: "请输入长度1~300的部门介绍",
            trigger: "brur",
          },
        ],
      },
    };
  },
  created() {
    this.loadEmployees();
    // 如果是编辑状态 触发函数实现编辑
    if (this.isEdit) {
      this.loadDepEmployees();
    }
  },
  methods: {
    // // 重置表单
    // resetForm(){
    //   this.$refs.deptForm.resetFields()
    // },
    // 发送请求 加载部门负责人
    async loadEmployees() {
      try {
        const res = await getEmployees();
        console.log("getEmployees", res);
        if (res.code !== 10000) return;
        // 赋值给list
        this.list = res.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 发送请求 加载表单数据
    async loadDepEmployees() {
      try {
        const res = await chakDepartments(this.id);
        console.log("chakDepartments", res);
        if (res.code !== 10000) return;
        // 赋值给list
        this.form = res.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 新增部门
    async doAdd() {
      try {
        // 缺少pid 父级部门的id
        const res = await addDepartments({ pid: this.id, ...this.form });
        console.log("addDepartments", res);
        if (res.code !== 10000) return this.$message.error(res.message);
        this.$message.success(res.message);
        // 重新渲染页面
        // 关闭弹层
        this.$emit("success");
      } catch (error) {
        console.log(error);
      }
    },
    // 实现编辑部门
    async doEdit() {
      try {
        const res = await updateDepartments(this.form);
        console.log("updateDepartments", res);
        if (res.code !== 10000) return this.$message.error(res.message);
        this.$message.success(res.message);
        // 重新渲染页面
        // 关闭弹层
        this.$emit("success");
      } catch (error) {
        console.log(error);
      }
      console.log("1111111111111111111111111");
    },
    // 确定
    hSubmit() {
      // 兜底校验
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return;
        // 校验成功
        this.isEdit ? this.doEdit() : this.doAdd();
      });
    },
    // 取消
    hCancel() {
      this.$emit("close");
    },
  },
  // watch监听调用函数
  // watch:{
  //   id:function (new_value,old_value){
  //     this.loadDepEmployees()
  //   }
  // }
};
</script>

